﻿/// <reference path="_References.js" />
(function () {
    document.addEventListener("deviceready", Lc.Events.OnDeviceReady, false);

    $(document).bind("mobileinit", function () {
        console.log("[mobileinit]");

        $.mobile.loadingMessage = "Laddar...";
        $.mobile.pageLoadErrorMessage = "Kunde inte ladda vyn";

        Lc.Settings.Load();
    });

    $(function () {
        $(document).delegate("#home", "pageinit", function () {
            console.log("#home > [pageinit]");

            // Load application view model.
            ko.applyBindings(new Lc.Models.AppViewModel());
        });

        $(document).delegate("#home", "pageshow", function () {
            console.log("#home > [pageshow]");

            setTimeout(function () {
                Lc.ShowAd("homeAdContainer");
            }, 1);
        });

        $(document).delegate("#play", "pageinit", function () {
            console.log("#play > [pageinit]");

            $("#playButtons input:checkbox").change(function () {
                if (Lc.suppressEvent) {
                    return;
                }

                console.log("#playButtons input:checkbox > [change]");

                Lc.UpdateNumberField("#playButtons", $(this));
                Lc.RecalculateUserNumbers();
            });

            $("#clearPlayButtons").click(function () {
                console.log("#clearPlayButtons > [click]");

                Lc.ClearNumberField("#playButtons");
                Lc.RecalculateUserNumbers();
            });
        });

        $(document).delegate("#play", "pagebeforeshow", function () {
            console.log("#play > [pagebeforeshow]");

            // Set default values for this page before user has had the chance to do anything.
            Lc.useAdditionalNumbers = true;
            Lc.maxNumbers = 11;

            // Recalculate in case there's new rows.
            Lc.RecalculateUserNumbers();
        });

        $(document).delegate("#play", "pageshow", function () {
            console.log("#play > [pageshow]");

            setTimeout(function () {
                Lc.ShowAd("playAdContainer");
            }, 1);
        });

        $(document).delegate("#manageNumbers", "pageshow", function () {
            console.log("#manageNumbers > [pageshow]");

            setTimeout(function () {
                Lc.ShowAd("manageNumbersAdContainer");
            }, 1);
        });

        $(document).delegate("#addRowDialog", "pageinit", function () {
            console.log("#addRowDialog > [pageinit]");

            $("#newRowButtons input:checkbox").change(function () {
                console.log("#newRowButtons input:checkbox > [change]");

                if (!Lc.suppressEvent) {
                    Lc.UpdateNumberField("#newRowButtons", $(this));
                }

                var options = $("#newRowButtons input:checked").length == Lc.maxNumbers ? "enable" : "disable";
                $("#saveRow").button(options);
            });

            $("#generateRandomNumbers").click(function () {
                console.log("#generateRandomNumbers > [click]");

                var min = 1,
		            max = 35,
		            random,
		            numbers = [];

                while (numbers.length < Lc.maxNumbers) {
                    random = Math.floor(Math.random() * (max - min + 1)) + min;

                    if (numbers.indexOf(random) == -1) {
                        numbers.push(random);
                    }
                }

                console.log("Random numbers generated: " + numbers.toString());

                Lc.ClearNumberField("#newRowButtons");

                $(numbers).each(function () {
                    $('#newRowButtons input[data-number="' + this + '"]').click().checkboxradio("refresh");
                });
            });

            $("#clearNewRowButtons").click(function () {
                console.log("#clearNewRowButtons > [click]");

                Lc.ClearNumberField("#newRowButtons");
            });
        });

        $(document).delegate("#addRowDialog", "pagebeforeshow", function () {
            console.log("#addRowDialog > [pagebeforeshow]");

            // Set default values for this page before user has had the chance to do anything.
            Lc.useAdditionalNumbers = false;
            Lc.maxNumbers = 7;
        });

        $(document).delegate("#addRowDialog", "pageshow", function () {
            console.log("#addRowDialog > [pageshow]");

            Lc.ClearNumberField("#newRowButtons");

            setTimeout(function () {
                Lc.ShowAd("addRowDialogAdContainer");
            }, 1);
        });
    });

    Lc.Events.OnDeviceReady = function () {
        console.log("[deviceready]");

        document.addEventListener("menubutton", Lc.Events.OnMenuKeyDown, false);
    };

    Lc.Events.OnMenuKeyDown = function () {
        console.log("[menubutton]");

        //REVIEW: Do better handling for slide up/down
        $("div[data-role='page'] div[data-role='header']").slideToggle();
    };

    Lc.UpdateNumberField = function (containerSelector, input) {
        console.log("UpdateNumberField(containerSelector = '" + containerSelector + "', input = '" + input + "')");

        var checked = $(containerSelector + " input:checked"),
		    defaultCount = checked.not(".additional").length,
		    totalCount = checked.length;

        if (Lc.useAdditionalNumbers) {
            if (input.is(":checked") && defaultCount > 7) {
                input.addClass("additional");
            } else {
                input.removeClass("additional");
            }
        }

        if (totalCount == Lc.maxNumbers) {
            $(containerSelector + " input:not(:checked)").checkboxradio("disable");
        } else {
            $(containerSelector + " input[disabled]").checkboxradio("enable");
        }
    };

    Lc.RecalculateUserNumbers = function () {
        console.log("RecalculateUserNumbers()");

        var checked = $("#playButtons input:checked"),
		    defaultNumbersList = checked.not(".additional").map(Lc.Utils.GetNumber),
		    additionalNumbersList = checked.filter(".additional").map(Lc.Utils.GetNumber),
		    userRows = $("#play .userRows li"),
		    userNumbers = userRows.find("[data-number]"),
            bestTotal = $("#play .userRows .bestTotal"),
		    maxDefaultCount = 0,
            maxAdditionalCount = 0;

        // Reset first.
        userNumbers.removeClass("ui-btn-active additional");

        // Add class for default numbers.
        $(defaultNumbersList).each(function () {
            Lc.Utils.AddClassToNumber(this, userNumbers, "ui-btn-active");
        });

        // Add class for additional numbers.
        $(additionalNumbersList).each(function () {
            Lc.Utils.AddClassToNumber(this, userNumbers, "ui-btn-active additional");
        });

        // Update number count.
        userRows.each(function () {
            var row = $(this),
			    defaultCount = row.find(".ui-btn-active:not(.additional)").length,
			    additionalCount = row.find(".ui-btn-active.additional").length;

            row.find(".ui-li-count .number").html(defaultCount);
            row.find(".ui-li-count .additional").html(additionalCount);

            if (defaultCount > maxDefaultCount || (defaultCount == maxDefaultCount && additionalCount > maxAdditionalCount)) {
                maxDefaultCount = defaultCount;
                maxAdditionalCount = additionalCount;
            }
        });

        bestTotal.find(".ui-li-count .number").html(maxDefaultCount);
        bestTotal.find(".ui-li-count .additional").html(maxAdditionalCount);

        if (maxDefaultCount == 4) {
            Lc.NotifyWinner();
        }
    };

    Lc.ClearNumberField = function (containerSelector) {
        console.log("ClearNumberField()");

        Lc.suppressEvent = true;

        $(containerSelector + " input:checked")
            .click()
		    .removeClass("additional")
		    .checkboxradio("refresh");

        $(containerSelector + " input:checkbox").checkboxradio("enable");

        Lc.suppressEvent = false;
    };

    Lc.ShowAd = function (id) {
        if (Lc.Settings.IsFreeVersion && Lc.HasConnection()) {
            console.log("Show ad on element: " + id);

            var ad, element = document.getElementById(id);
            element.innerHTML = "";

            ad = _admob.fetchAd(element);
        }
    };

    Lc.NotifyWinner = function () {
        console.log("notifyWinner");

        if (!navigator.notification) {
            return;
        }

        if (Lc.Settings.BeepOnNotify) {
            navigator.notification.beep(1);
        }

        navigator.notification.vibrate(0);
    };

    Lc.Utils.GetNumber = function (index, item) {
        return $(item).jqmData("number");
    };

    Lc.Utils.AddClassToNumber = function (number, toCollection, className) {
        toCollection.filter('[data-number="' + number + '"]').addClass(className);
    };

    Lc.HasConnection = function () {
        if (!navigator.network) {
            return true;
        }

        var networkState = navigator.network.connection.type,
            states = {};

        states[Connection.UNKNOWN] = 'Unknown connection';
        states[Connection.ETHERNET] = 'Ethernet connection';
        states[Connection.WIFI] = 'WiFi connection';
        states[Connection.CELL_2G] = 'Cell 2G connection';
        states[Connection.CELL_3G] = 'Cell 3G connection';
        states[Connection.CELL_4G] = 'Cell 4G connection';
        states[Connection.NONE] = 'No network connection';

        console.log('Connection type: ' + states[networkState]);

        return networkState != Connection.NONE;
    };
})();